<template>
	<view class="padding">
		<view ref="topBox" id="topBox" class="topBox">
			<uni-row class="demo-uni-row">
				<uni-col :span="24">
					<template v-if="pageSetting.showTopinfo">
						<uni-row class="demo-uni-row">
							<uni-col :span="24">
								<view class="demo-uni-col dflex">
									<view class="border-radius bg-blue-gradient margin padding dflex">
										<text class="fs-32 ft-white fwb">已签：</text>
										<h2 class="ft-white">&nbsp{{topInfos.data1[0].signamount}}&nbsp元
										</h2>
									</view>
									<view class="border-radius bg-red-gradient margin padding dflex">
										<text class="fs-32 ft-white fwb">全年：</text>
										<h2 class="ft-white">
											&nbsp{{topInfos.data1[0].totalamount}}&nbsp元
										</h2>
									</view>
									<view class="border-radius bg-green-gradient margin padding dflex">
										<text class="fs-32 ft-white fwb">已收：</text>
										<h2 class="ft-white">
											&nbsp{{topInfos.data1[0].receipts}}&nbsp元
										</h2>
									</view>
									<view class="border-radius bg-purple-gradient margin padding dflex">
										<text class="fs-32 ft-white fwb">应收：</text>
										<h2 class="ft-white">
											&nbsp{{topInfos.data1[0].receivable}}&nbsp元
										</h2>
									</view>
									<view class="border-radius bg-blue-gradient2 margin padding dflex">
										<text class="fs-32 ft-white fwb">在谈：</text>
										<h2 class="ft-white">
											&nbsp{{topInfos.data1[0].business}}&nbsp元
										</h2>
									</view>
								</view>
							</uni-col>
						</uni-row>
					</template>
				</uni-col>
			</uni-row>

			<view class="demo-uni-col dflex-b padding-lr-sm padding-tb-sm border-bottom">
				<h2 v-if="pageSetting.showTopinfo">
					<text
						v-if="pageSetting.ganttType === 'project'">{{ganttSeachsetting.period}}年度{{topInfos.data2[ganttSeachsetting.teamset].text}}项目甘特图</text>
					<text v-else="pageSetting.ganttType === 'task'"> {{contractInfos.data1[0].contractname}}
						工作任务总览</text>
				</h2>
				<view class="topSet">
					<view class="cctype">
						<uni-data-select v-model="ganttSeachsetting.period" :localdata="yearRange" @change="setYear"
							:clear="false"></uni-data-select>
					</view>
					<view v-if="pageSetting.showTopinfo" class="cctype">
						<uni-data-select v-model="ganttSeachsetting.teamset" :localdata="topInfos.data2"
							@change="setTeam" :clear="false"></uni-data-select>
					</view>
				</view>
			</view>
		</view>
		<view class="demo-uni-row padding dflex-bs">
			<view :span="18" class="flex1">
				<view class="demo-uni-col dark">
					<view style="height: 70px;">
						<canvas
							:style="{width: pageSetting.canvasWidth + 'px', height: 70 + 'px', position: 'absolute'}"
							:canvas-id="Title"></canvas>
					</view>
					<view class="canvasBox" :style="{position: 'relative', height: pageSetting.canvasHeight + 'px'}"
						ref='canvasBox'>
						<canvas
							:style="{width: pageSetting.canvasWidth + 'px', height: pageSetting.canvasHeight + 'px', position: 'absolute', 'z-index': 2}"
							:canvas-id="Gantt"></canvas>
						<canvas
							:style="{width: pageSetting.canvasWidth + 'px', height: pageSetting.canvasHeight + 'px', position: 'absolute', 'z-index': 4}"
							:canvas-id="Pointer" @click="handleCanvasClick" @touchstart="handleTouchStart"
							@touchmove="handleTouchMove" @touchend="handleTouchEnd"></canvas>
						<canvas
							:style="{width: pageSetting.canvasWidth + 'px', height: pageSetting.canvasHeight + 'px', position: 'absolute', 'z-index': 1}"
							:canvas-id="Shadow"></canvas>
					</view>
				</view>
			</view>
			<view :span="6" style="width: 320px;">
				<view class="demo-uni-col light">
					<template v-if="pageSetting.ganttType === 'task'">
						<view class="dflex pageing" style="height: 45px;">
							<view @click="backToProjectShow" class="btn">
								<uni-icons type="arrow-left" color="#1faccc" size="18" class="icon"></uni-icons>
								<text style="color: #1faccc;">返回</text>
							</view>
							<view style="flex:1"></view>
							<button @click="projectScoll('previous')" class="btn">
								<uni-icons type="left" color="#5e6d82" size="18" class="icon"></uni-icons>
								<text>上一个</text></button>
							<button @click="projectScoll('next')" class="btn" style="padding:3px 5px 3px 15px">
								<text>下一个</text>
								<uni-icons type="right" color="#5e6d82" size="18" class="icon"></uni-icons></button>
						</view>
					</template>
					<template
						v-if="pageSetting.shadowLine && pageSetting.isEdit === false && pageSetting.ganttType === 'project' ">
						<uni-section :title="'项目：'+(contractInfos.data1[0].contractname || '')" titleFontSize='18px'
							type="line" @click="projectGantts">
							<template v-slot:right>
								<text style="color: #1faccc;cursor: pointer;">详情 ></text>
							</template>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;"
											class="ft-dark-3">负责人:</text><text>{{contractInfos.data1[0].user_name}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">项目周期:</text>
										<text>{{contractInfos.data1[0].startdate.substring(0,10)}} </text>
										<text class="ft-dark-3 padding-lr-xs">至 </text>
										<text>{{contractInfos.data1[0].enddate.substring(0,10)}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">签约日期:</text>
										<text>{{contractInfos.data1[0].signdate.substring(0,10)||'--'}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">合同金额:</text>
										<text>{{contractInfos.data1[0].amount||'--'}}&nbsp元</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">已收款额:</text>
										<text>{{contractInfos.data1[0].receipts||'--'}}&nbsp元</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">应收款额:</text>
										<text>{{contractInfos.data1[0].receivable||'--'}}&nbsp元</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;" class="ft-dark-3">项目风险:</text>
										<text v-if="contractInfos.data1[0].risknum == 0">暂无风险</text>
										<text v-else="contractInfos.data1[0].risknum !== 0"
											style="color: red;">含{{contractInfos.data1[0].risknum}}个风险，请查看项目详情。</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col padding-tb-xs">
										<template v-if="contractInfos.data2.length > 0">
											<view label="" v-for="(i,k) in contractInfos.data2" :key="i.no"
												class="margin-bottom-sm  ">
												<template v-if="!i.show">
													<view class=" border dflex-fs  border-radius bg-main-2 padding-xs ">
														<view class="dblock">
															<view class="dflex">
																<label class="ft-dark-3"
																	style="cursor:default">{{i.content}}：</label>
																<text>{{i.amount}}&nbsp元&nbsp&nbsp</text>
															</view>
															<view class="dflex">
																<label v-if="i.actual_date.length !== 0 "
																	class="ft-dark-3"
																	style="cursor:default">回款日期：</label>
																<label v-else class="ft-dark-3"
																	style="cursor:default">计划日期：</label>
																<text v-if="i.actual_date.length !== 0 ">
																	{{i.actual_date}}
																</text>
																<text v-else>
																	{{i.date.substring(0,10)}}
																</text>
															</view>
														</view>
														<view style="width: 62.5px;" class="padding-top-xxs ">
															<b style=""
																class="padding-right-xs ft-blue">[{{i.status}}]</b>
														</view>
													</view>
												</template>
											</view>
										</template>

									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex-fs padding-tb-xs">
										<text style="width: 65px;min-width: 65px;">项目成员:</text>
										<view class="dflex" style="flex-wrap: wrap;">
											<view v-for="i in contractInfos.data3" :key="i.no"
												class="margin-bottom-sm dflex border-blue border-radius-sm padding-lr-xs margin-right-sm"
												style="height: 32px; line-height: 32px;cursor: pointer;"
												@click="chooseMember(i)">
												<uni-icons type="person" size="20" color="#ababab" />
												<text>{{i.user_name}}</text>
											</view>
										</view>
									</view>
								</uni-col>
							</uni-row>
						</uni-section>
					</template>
					<template
						v-if="pageSetting.shadowLine && pageSetting.isEdit === false && pageSetting.ganttType === 'task' ">
						<uni-section :title="touchLineinfo.text" titleFontSize='18px' type="line">
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text
											:style="{fontSize: '16px', color: touchLineinfo.status === '未完成' ? 'dimgray' : 'blue'}">{{touchLineinfo.status}}&nbsp</text>
										<text v-if="touchLineinfo.status !== '已完成' && touchLineinfo.risktips !== '无风险'"
											style="color: red; font-size: 16px;">{{touchLineinfo.risktips}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text style="width: 65px;">任务起始:</text>
										<text>{{touchLineinfo.start.substring(0,10)}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col>
									<view class="demo-uni-col dark dflex padding-tb-xs">
										<text
											style="width: 65px;">{{touchLineinfo.status === '未完成' ? '预计完成:' : '完成时间:'}}</text>
										<text>{{touchLineinfo.end.substring(0,10)}}</text>
									</view>
								</uni-col>
							</uni-row>
							<uni-row class="demo-uni-row">
								<uni-col v-for="i in taskInfos.data2">
									<view class="demo-uni-col dark dflex padding-tb-xs"
										v-if="i.transactiondetailid === touchLineinfo.id">
										<text style="width: 65px;">{{i.user_name}}</text>
										<text style="width: 100px;">{{i.actualhours === '' ? 0 : i.actualhours}}
											小时</text>
										<text :style="{fontSize: '16px', 
											color: i.status === '未开始' ? 'gray' : 
												   i.status === '未完成' ? 'dimgray':
											'blue'}">{{i.status}}</text>
									</view>
								</uni-col>
							</uni-row>
						</uni-section>
					</template>
				</view>
			</view>
		</view>
	</view>
	<uni-popup ref="popup" @change="change">
		<view class="popup-content border-radius bg-main-2"
			:style="{width: (screenWidth + detailsBoxWidth) * 0.8 + 'px',height: screenHeight * 0.8 + 'px'}">
			<view @click="closepopup" class="dflex-c" style="position: absolute;top:15px;right: 15px;cursor: pointer;width: 25px;height: 25px;">
				<uni-icons type="closeempty" color="#5e6d82" size="18" class="icon"></uni-icons>
			</view>
			<view class="dflex-c " style="height: 65vh;">
				<text class="text fs-120">测试内容</text>
			</view>
		</view>
	</uni-popup>
</template>
<script setup>
	import {
		onMounted,
		onUnmounted,
		nextTick,
		ref,
		getCurrentInstance,
		computed
	} from 'vue';
	import HttpService from '../../api/index';
	const httpService = new HttpService('https://saastest.youerp.cn/saas_N912d04')
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app";
	const {
		proxy
	} = getCurrentInstance();

	const Gantt = ref('ganttChart'); //定义gantt层
	const Pointer = ref('pointerLine'); //定义pointer层
	const Shadow = ref('shadowLayer'); //定义Shadow层
	const Title = ref('titleLayer'); //定义Title层
	const canvasBox = ref(null);
	const detailsBoxWidth = 420;
	const screenWidth = uni.getSystemInfoSync().windowWidth - detailsBoxWidth; //获取屏幕宽度
	const screenHeight = uni.getSystemInfoSync().windowHeight; //获取屏幕高度
	const topBox = ref(null);
	const topBoxHeight = ref(93.59 + 15 + 54.59 + 15 + 70);
	const leftEdgeWeight = ref(15)
	const change = () => {}
	const pageSetting = ref({
		canvasWidth: screenWidth, //画布宽度
		canvasHeight: 300, //画布高度
		topY: 0, //离原点的Y距离
		drawX: 30, //起始绘画X点
		endX: 20, //X轴长度
		drawY: 30, //起始绘画Y点
		intervalY: 40, //Y间隔
		lineWidth: 30, //线宽
		isDragging: false, //拖拽开关
		direction: 'right', //画线方向（只在拖拽时生效）
		timeType: 'month', //时间类型:目前三种hour,day,month，会影响时间轴的计算和显示
		startpoint: '', //整张甘特图起点
		endpoint: '', //整张甘特图终点
		durationDays: 0, //时间轴内所含天数
		durationMinutes: 0, //时间轴内所含分钟数
		fontSize: 14, //默认线段字体的字号
		fontcolor: '#FFFFFF', //线段字体的默认颜色
		shadowLine: false, //显示阴影
		isEdit: false, //是否为编辑状态
		addNew: false, //是否是新增线段
		canSave: false, //是否能保存
		canMove: false, //是否可移动
		fps: 60, //屏幕帧数
		smooth: 60, //平滑系数，10-60区间，越高越平滑，动画时间略长
		totalStep: 0, //由fps和smooth计算得出的动画总步数，用于计算每帧的动画移动像素
		showPercent: true, //是否显示百分比
		pointerID: 0, //pointer的ID
		showTopinfo: false,
		ganttType: 'project',
		presentProjectID: '',
		presentContractID: '',
	});
	//甘特图查询参数设置
	const ganttSeachsetting = ref({
		type: 'all',
		ganttid: '', //甘特项目ID
		personid: '', //人员ID，用于查询单人目前的任务
		period: '', //查询周期范围
		teamset: 0,
	});
	const yearRange = ref([]);
	const topInfos = ref(); // 看板类整体信息
	const projectInfos = ref();
	const contractInfos = ref({
		data1: [{
			user_name: '',
			signdate: '',
			startdate: '',
			enddate: ''
		}],
		data2: [],
		data3: []
	}); //合同信息
	//内置的甘特图颜色
	const ganttColor = ref([{
			key: 1,
			value: "rgba(75, 119, 190, 0.5)"
		},
		{
			key: 2,
			value: "rgba(164, 80, 100, 0.5)"
		},
		{
			key: 3,
			value: "rgba(114, 176, 137, 0.5)"
		},
		{
			key: 4,
			value: "rgba(218, 124, 60, 0.5)"
		},
		{
			key: 5,
			value: "rgba(84, 160, 227, 0.5)"
		},
		{
			key: 6,
			value: "rgba(221, 141, 186, 0.5)"
		},
		{
			key: 7,
			value: "rgba(170, 205, 105, 0.5)"
		},
		{
			key: 8,
			value: "rgba(235, 134, 87, 0.5)"
		},
		{
			key: 9,
			value: "rgba(113, 177, 177, 0.5)"
		},
		{
			key: 10,
			value: "rgba(207, 161, 96, 0.5)"
		},
		{
			key: 11,
			value: "rgba(147, 134, 192, 0.5)"
		},
		{
			key: 12,
			value: "rgba(198, 151, 123, 0.5)"
		},
		{
			key: 13,
			value: "rgba(132, 183, 108, 0.5)"
		},
		{
			key: 14,
			value: "rgba(231, 115, 77, 0.5)"
		},
		{
			key: 15,
			value: "rgba(101, 146, 166, 0.5)"
		},
		{
			key: 16,
			value: "rgba(20, 157, 86, 0.5)"
		},
	]);

	let axisPoints = {
		start: '',
		end: '',
		middle: '',
		points: 0,
	}; //定义甘特图坐标点数组
	let coloredPool = []; //定义已用颜色池
	let orgGCP = []; //定义组织原始甘特图颜色池
	const valueX = screenWidth - pageSetting.value.drawX - pageSetting.value.endX; //X轴长度
	const touchLineinfo = ref(); //记录当前点击的线信息
	const touchLine_left = ref(); //记录当前点击的线左侧
	const touchLine_right = ref(); //记录当前点击的线右侧
	const line_cache = ref(); //缓存线信息
	const taskInfos = ref(); //项目内任务信息

	const setYear = (y) => {
		ganttSeachsetting.value.period = y;
		pageSetting.value.ganttType = 'project';
		let teamname = '';
		if (topInfos.value.data2[ganttSeachsetting.value.teamset].text !== '全公司') {
			teamname = topInfos.value.data2[ganttSeachsetting.value.teamset].text;
		};
		cleanDrawgantt();
		getGanttDatas(ganttSeachsetting.value.period, teamname);
	};
	const setTeam = (n) => {
		pageSetting.value.ganttType = 'project';
		let teamname = '';
		if (topInfos.value.data2[n].text !== '全公司') {
			teamname = topInfos.value.data2[n].text;
		};
		cleanDrawgantt();
		getGanttDatas(ganttSeachsetting.value.period, teamname);
	};

	const getData = async (type, param) => {
		return new Promise((resolve, reject) => {
			try {
				httpService.request({
					url: '/webapi/eidData.ashx?oper=' + type,
					data: param,
					method: 'GET'
				}).then((res) => {
					if (res.status == '1') {
						resolve(res);
					} else {
						reject('获取信息失败' + res.msg)
					}
				})
			} catch (error) {
				console.error(error)
			}
		});
	};
	//找单一项目的信息，用于下穿的
	const getTaskinfo = async (taskid) => {
		let info = await getData("LTTG_Multifunction", {
			storedPro: 'P_View_Gantt_Task',
			paraNum: 1,
			resultSetNum: 2,
			para1: taskid
		});
		taskInfos.value = info;
		console.log(taskInfos.value);
	};
	//合同信息
	const getContractinfo = async (tid, cid) => {
		let info = await getData("LTTG_Multifunction", {
			storedPro: 'P_View_Gantt_Contract',
			paraNum: 2,
			resultSetNum: 3,
			para1: tid,
			para2: cid
		});
		console.log(info)
		contractInfos.value = info;
		console.log(contractInfos.value.data2);
		contractInfos.value.data2.forEach((item, i) => {
			contractInfos.value.data2[i]["show"] = areAllValuesEmpty(item);
		})
		console.log(contractInfos.value.data2);
	};
	//个人项目信息
	const getTask_info_with_person = async (year, uid) => {
		let info = await getData("LTTG_Multifunction", {
			storedPro: 'P_View_Gantt_Person',
			paraNum: 2,
			resultSetNum: 1,
			para1: year,
			para2: uid
		});
		// console.log(info);
	};
	//总体看板和信息
	const getGantt_TopInfos = async (year, teamname) => {
		let info = await getData("LTTG_Multifunction", {
			storedPro: 'P_View_Gantt_Top',
			paraNum: 2,
			resultSetNum: 2,
			para1: year,
			para2: teamname //''为全部信息
		});
		topInfos.value = info;
	};
	//绘制任务类甘特图
	const buildTaskGantt = () => {
		drawAxisX('');
		pageSetting.value.canvasHeight = pageSetting.value.drawY + (taskInfos.value.data1.length + 1) *
			(pageSetting.value.intervalY);
		taskInfos.value.data1.forEach((item, index) => {
			item.x1 = 0;
			item.x2 = 0;
			item.xp = 0;
			item.y = 0;
			item.text = item.content;
			item.id = item.eid_transactiondetail_id;
			item.start = item.estimatesdate;
			item.end = item.estimateedate.substring(0, 10) + ' 23:59:59';
			item.color = ganttColor.value.find(obj => obj.key == item.no).value;
			item.index = index;
			item.colorkey = item.no;
			item.drawID = 0;
			item.drawStep = 0;
			item.drewX = 0;
			item.percent = item.status === '已完成' ? 100 : 0;
			delete item.eid_transactiondetail_id;
			delete item.estimatesdate;
			delete item.estimateedate;
			delete item.no;
			delete item.content;
		});
		for (const line of taskInfos.value.data1) {
			dataTransfer(line);
		}
		taskInfos.value.data1.sort((a, b) => a.index - b.index);
		// console.log('taskinfos', taskInfos.value);
		line_cache.value = taskInfos.value.data1;
		cleanDrawgantt();
		cleanDrawpointer();
		mutiplyShow('animation');
		if (line_cache.value.length == 0) {
			touchLineinfo.value = 'None';
			cleanDrawpointer();
			drawShadowLine('clear');
		} else {
			isDrag(line_cache.value[0].x1, line_cache.value[0].y + topBoxHeight.value);
		}
	};
	//项目的甘特图信息
	const getGanttDatas = async (year, teamname) => {
		findPeriod(ganttSeachsetting.value.type, year); //找到时间刻度周期
		drawAxisX(''); //画x轴坐标轴和刻度线
		let info = await getData("LTTG_Multifunction", {
			storedPro: 'P_View_Gantt_Project',
			paraNum: 2,
			resultSetNum: 1,
			para1: year,
			para2: teamname //''为全部信息
		});
		projectInfos.value = info.data1;
		//计算初始画布高度
		pageSetting.value.canvasHeight = pageSetting.value.drawY + (projectInfos.value.length + 1) *
			(pageSetting.value.intervalY);
		projectInfos.value.forEach((item, index) => {
			item.x1 = 0;
			item.x2 = 0;
			item.xp = 0;
			item.y = 0;
			item.text = item.name;
			item.id = item.eid_transaction_id;
			item.start = item.sdate + ' 00:00:00';
			// item.end = item.edate + ' 23:59:59';
			item.end = item.edate + ' 00:00:00';
			item.color = ganttColor.value.find(obj => obj.key == item.no)
				.value;
			item.index = index;
			item.colorkey = item.no;
			item.drawID = 0;
			item.drawStep = 0;
			item.drewX = 0;
			item.percent = parseInt(100 * parseInt(item.finishnum) / parseInt(item.num));
			delete item.eid_transaction_id;
			delete item.sdate;
			delete item.edate;
			delete item.no;
			delete item.name;
		});
		//按线数据转换生成x轴的对应坐标和颜色
		for (const line of projectInfos.value) {
			dataTransfer(line);
		}
		//按照index排序
		projectInfos.value.sort((a, b) => a.index - b.index);
		line_cache.value = projectInfos.value;
		// console.log('lineinfo',line_cache.value);
		//画甘特图
		mutiplyShow('animation');
		if (line_cache.value.length == 0) {
			touchLineinfo.value = 'None';
			cleanDrawpointer();
			drawShadowLine('clear');
		} else {
			//默认选中第一条甘特图，找到相关合同信息
			isDrag(line_cache.value[0].x1, line_cache.value[0].y + topBoxHeight.value);
			getContractinfo(line_cache.value[0].id, line_cache.value[0].contractid);
		}
	};
	//项目详细甘特图显示
	const projectGantts = () => {
		pageSetting.value.ganttType = 'task';
		let psdate = contractInfos.value.data1[0].startdate + ' 00:00:00';
		let pedate = contractInfos.value.data1[0].enddate + ' 23:59:59';
		findPeriod('project', '', psdate, pedate);
		// console.log(psdate, pedate);
		buildTaskGantt();
	};
	//返回项目类甘特图
	const backToProjectShow = () => {
		pageSetting.value.ganttType = 'project';
		let teamname = '';
		if (topInfos.value.data2[ganttSeachsetting.value.teamset].text !== '全公司') {
			teamname = topInfos.value.data2[ganttSeachsetting.value.teamset].text;
		};
		cleanDrawgantt();
		getGanttDatas(ganttSeachsetting.value.period, teamname);
	};
	//翻动展示项目内任务
	const projectScoll = (direct) => {
		let n = projectInfos.value.find(i => i.id === pageSetting.value.presentProjectID).index;
		n = direct === 'next' ? n + 1 : n - 1;
		if (n < 0) {
			n = projectInfos.value.length - 1;
		} else if (n > projectInfos.value.length - 1) {
			n = 0;
		}
		pageSetting.value.presentProjectID = projectInfos.value[n].id;
		pageSetting.value.presentContractID = projectInfos.value[n].contractid;
		getContractinfo(pageSetting.value.presentProjectID, pageSetting.value.presentContractID).then(() => {
			getTaskinfo(pageSetting.value.presentProjectID).then(() => {
				projectGantts();
			});
		});
	};
	//画X时间轴
	const drawAxisX = (type) => {
		const ctx = uni.createCanvasContext(Title.value, proxy);
		const textY = 20; //时间轴两端文字位置
		const axisY = 42; //时间轴Y轴位置
		let axisWidth = screenWidth - pageSetting.value.endX - pageSetting.value.drawX; //时间轴像素长度
		ctx.clearRect(0, 0, screenWidth, 70);
		let intervalpx = axisWidth / 30; //刻度间隔
		//绘制白色背景不透明
		ctx.setFillStyle('rgba(255,255,255,1)');
		ctx.fillRect(0, 0, screenWidth, 70);
		ctx.stroke();
		ctx.draw(true);
		//绘制时间轴上的刻度
		for (let i = 1; i < 31; i++) {
			ctx.moveTo(pageSetting.value.drawX + intervalpx * i - 1, axisY);
			ctx.lineTo(pageSetting.value.drawX + intervalpx * i + 1, axisY);
			ctx.setLineWidth(5);
			ctx.setStrokeStyle('rgba(0,0,0,0.2)');
			ctx.stroke();
			ctx.draw(true);
		}
		//绘制刻度的两端和中间
		ctx.moveTo(pageSetting.value.drawX - 1, axisY);
		ctx.lineTo(pageSetting.value.drawX + 1, axisY);
		ctx.moveTo(screenWidth - pageSetting.value.endX - 1, axisY);
		ctx.lineTo(screenWidth - pageSetting.value.endX + 1, axisY);
		ctx.moveTo(pageSetting.value.drawX + axisWidth / 2 - 1, axisY);
		ctx.lineTo(pageSetting.value.drawX + axisWidth / 2 + 1, axisY);
		ctx.setLineWidth(10);
		ctx.setStrokeStyle('rgba(0,0,0,0.5)');
		ctx.stroke();
		//绘制两端文字
		ctx.setFontSize(14);
		ctx.setFillStyle('#000000');
		if (pageSetting.value.timeType === 'hour') {
			ctx.fillText(pageSetting.value.startpoint.slice(-8).substring(0, 5), pageSetting.value.drawX - 20, textY);
			ctx.fillText(pageSetting.value.endpoint.slice(-8).substring(0, 5), screenWidth - pageSetting.value.endX -
				20, textY);
		} else {
			if (pageSetting.value.ganttType === 'project') {
				ctx.fillText(pageSetting.value.startpoint.substring(0, 10).slice(-5), pageSetting.value.drawX - 20,
					textY);
				ctx.fillText(pageSetting.value.endpoint.substring(0, 10).slice(-5), screenWidth - pageSetting.value
					.endX -
					20, textY);
			} else {
				ctx.fillText(pageSetting.value.startpoint.substring(0, 10), pageSetting.value.drawX - 20, textY);
				ctx.fillText(pageSetting.value.endpoint.substring(0, 10), screenWidth - pageSetting.value.endX -
					60, textY);
			}
		}
		ctx.draw(true);
		//移动状态下绘制（注意非h5环境不生效）
		if (type === 'showpointer') {
			ctx.setFontSize(12);
			ctx.setFillStyle(colorOpacity(touchLineinfo.value.color, 1));
			let starttime = pageSetting.value.timeType === 'hour' ? touchLineinfo.value.start.slice(-8).substring(0,
					5) :
				touchLineinfo.value.start.substring(
					0, 10).slice(-5);
			let endtime = pageSetting.value.timeType === 'hour' ? touchLineinfo.value.end.slice(-8).substring(0, 5) :
				touchLineinfo.value.end.substring(
					0, 10).slice(-5);
			ctx.moveTo(touchLineinfo.value.x1 + 2, 60);
			ctx.lineTo(touchLineinfo.value.x1, 60);
			ctx.setStrokeStyle(colorOpacity(touchLineinfo.value.color, 0.3));
			ctx.setLineWidth(30);
			ctx.stroke();
			ctx.fillText(starttime, touchLineinfo.value.x1 - 16, 33);
			ctx.fillText(endtime, touchLineinfo.value.x2 - 16, 60);
		}
		ctx.draw(true);
	};

	//绘制阴影区域
	const drawShadowLine = (action) => {
		const ctx = uni.createCanvasContext(Shadow.value, proxy);
		ctx.clearRect(0, 0, screenWidth, 500);
		if (action === 'clear') {
			pageSetting.value.shadowLine = false;
			ctx.stroke();
			ctx.draw(true);
			return;
		}
		ctx.moveTo(0, touchLineinfo.value.y);
		ctx.lineTo(screenWidth, touchLineinfo.value.y);
		ctx.setStrokeStyle('rgba(100,100,100,0.13)');
		ctx.setLineWidth(pageSetting.value.lineWidth + 10);
		pageSetting.value.shadowLine = true;
		ctx.stroke();
		ctx.draw(true);
	};

	//绘制移动状态下的时间和刻度线
	const drawPointer = () => {
		const ctx = uni.createCanvasContext(Pointer.value, proxy);
		ctx.clearRect(0, 0, screenWidth, pageSetting.value.canvasHeight);
		let y = touchLineinfo.value.y - pageSetting.value.lineWidth / 2;
		let opacity = 1;
		let decreasing = true;
		ctx.moveTo(touchLineinfo.value.x2 - 2, y / 2);
		ctx.lineTo(touchLineinfo.value.x2, y / 2);
		ctx.moveTo(touchLineinfo.value.x1 + 2, y / 2);
		ctx.lineTo(touchLineinfo.value.x1, y / 2);

		ctx.setStrokeStyle(colorOpacity(touchLineinfo.value.color, 0.3));
		ctx.setLineWidth(y);
		ctx.stroke();
		ctx.draw(true);
		// console.log(pageSetting.value.pointerID);
	};
	//静态绘制直线图
	const drawLine = (lineInfo, type) => {
		const ctx = uni.createCanvasContext(Gantt.value, proxy);
		ctx.lineCap = 'butt';
		ctx.setLineWidth(pageSetting.value.lineWidth);
		let sx = pageSetting.value.direction === 'right' ? lineInfo.x1 : lineInfo.x2;
		let ex = pageSetting.value.direction === 'right' ? lineInfo.x2 : lineInfo.x1;
		if (type === 'move') {
			ctx.clearRect(0, lineInfo.y - pageSetting.value.lineWidth / 2, screenWidth, pageSetting.value
				.lineWidth + 2); //x,y,width,height
			ctx.setStrokeStyle(lineInfo.color);
			ctx.moveTo(sx, lineInfo.y);
			ctx.lineTo(ex, lineInfo.y);
			ctx.stroke();
			ctx.draw(true);
		} else {
			ctx.clearRect(sx, lineInfo.y - pageSetting.value.lineWidth / 2, screenWidth, pageSetting.value
				.lineWidth); //x,y,width,height
			ctx.setStrokeStyle(colorOpacity(lineInfo.color, 1));
			ctx.moveTo(sx, lineInfo.y);
			ctx.lineTo(lineInfo.xp, lineInfo.y);
			ctx.stroke();
			ctx.draw(true);
			ctx.setStrokeStyle(lineInfo.color);
			ctx.moveTo(lineInfo.xp, lineInfo.y);
			ctx.lineTo(ex, lineInfo.y);
			ctx.stroke();
			ctx.draw(true);
		}
		ctx.font = pageSetting.value.fontSize + 'px san-serif';
		let textwidth = parseInt(ctx.measureText(lineInfo.text).width);
		let tdinfo = textDrawAxisX(lineInfo, textwidth);
		ctx.setFontSize(pageSetting.value.fontSize);
		ctx.setFillStyle(tdinfo.color);
		ctx.fillText(tdinfo.showtext, tdinfo.x, tdinfo.y);
		ctx.draw(true);
	};
	//动态画线--动画
	const drawLineAnimation = (lineInfo) => {
		const line = uni.createCanvasContext(Gantt.value, proxy);
		lineInfo.drewX = lineInfo.drewX === 0 ? lineInfo.x1 : lineInfo.drewX;
		let dpx = 0;
		if (lineInfo.drewX < lineInfo.x2) {
			line.moveTo(lineInfo.drewX, lineInfo.y);
			lineInfo.drawStep++;
			dpx = getStep(lineInfo.x2 - lineInfo.x1, pageSetting.value.smooth, pageSetting.value.totalStep, lineInfo
				.drawStep);
			if (lineInfo.drewX < lineInfo.xp) {
				lineInfo.drewX = lineInfo.drewX + dpx;
				lineInfo.drewX = lineInfo.drewX >= lineInfo.xp ? lineInfo.xp : lineInfo.drewX;
				line.setStrokeStyle(colorOpacity(lineInfo.color, 1));
			} else {
				lineInfo.drewX = lineInfo.drewX + dpx;
				lineInfo.drewX = lineInfo.drewX >= lineInfo.x2 ? lineInfo.x2 : lineInfo.drewX;
				line.setStrokeStyle(lineInfo.color);
			}
			line.lineTo(lineInfo.drewX, lineInfo.y);
			line.setLineWidth(pageSetting.value.lineWidth);
			line.stroke();
		} else {
			clearInterval(lineInfo.drawID);
			lineInfo.drewX = 0;
			lineInfo.drawStep = 0;
			line.font = pageSetting.value.fontSize + 'px san-serif';
			let textwidth = parseInt(line.measureText(lineInfo.text).width);
			let tdinfo = textDrawAxisX(lineInfo, textwidth);
			line.setFontSize(pageSetting.value.fontSize);
			line.setFillStyle(tdinfo.color);
			line.fillText(tdinfo.showtext, tdinfo.x, tdinfo.y);
		}
		line.draw(true);
	};
	//处理文字信息
	const textDrawAxisX = (lineInfo, textwidth) => {
		// console.log(lineInfo);
		let showtext = '';
		let text = lineInfo.text;
		let adjusttextwidth = (textwidth + pageSetting.value.fontSize * 4); //(增加百分比显示的长度，大概是3个字符)
		let limit = pageSetting.value.fontSize * 7; //最大字符长度是7个汉字
		if (textwidth > limit) {
			let n = parseInt(lineInfo.text.length * limit / textwidth);
			text = lineInfo.text.substring(0, n) + '...'; //多于某个长度后截断字符
			adjusttextwidth = limit + pageSetting.value.fontSize * 4;
		}
		if (pageSetting.value.ganttType === 'project') {
			showtext = pageSetting.value.showPercent ? `${text} (${lineInfo.percent}%)` : lineInfo.text;
		} else {
			if (lineInfo.risktips !== '无风险' && lineInfo.status !== '已完成') {
				showtext = `${text} (${lineInfo.risktips})`;
			} else {
				showtext = `${text} (${lineInfo.status})`;
			}
		}
		let linewidth = lineInfo.x2 - lineInfo.x1;
		let leftwidth = lineInfo.x1;
		let rightwidth = screenWidth - lineInfo.x2;
		let y = lineInfo.y + pageSetting.value.fontSize / 2 - 2;
		let fontcolor = pageSetting.value.fontcolor;
		let x = lineInfo.x1 + (lineInfo.x2 - lineInfo.x1) / 2 - adjusttextwidth / 2;
		// console.log(textwidth,adjusttextwidth,x);
		if (adjusttextwidth > linewidth) {
			if (leftwidth > adjusttextwidth + 40) {
				x = lineInfo.x1 - 30 - adjusttextwidth;
			} else {
				x = lineInfo.x2 + 10;
			}
			fontcolor = colorOpacity(lineInfo.color, 1);
		}
		return {
			showtext: showtext,
			color: fontcolor,
			x: x,
			y: y
		}
	};

	//删除gantt层区域内图像
	const cleanDrawgantt = () => {
		const ctx = uni.createCanvasContext(Gantt.value, proxy)
		ctx.clearRect(0, 0, screenWidth, pageSetting.value.canvasHeight); //x,y,width,height
		ctx.draw(true);
	};
	//删除pointer层区域内图像
	const cleanDrawpointer = () => {
		const ctx = uni.createCanvasContext(Pointer.value, proxy)
		ctx.clearRect(0, 0, screenWidth, pageSetting.value.canvasHeight); //x,y,width,height
		ctx.draw(true);
	};
	//删除Title层区域内图像
	const cleanDrawtitle = () => {
		const ctx = uni.createCanvasContext(Title.value, proxy)
		ctx.clearRect(0, 0, screenWidth, pageSetting.value.canvasHeight); //x,y,width,height
		ctx.draw(true);
	};

	//找到三条线
	const defineThreelinesinfo = (line) => {
		// console.log("line info at function defineThreelinesinfo:", line);
		touchLineinfo.value = line;
		// console.log(touchLineinfo.value);
		if (pageSetting.value.ganttType === 'project') {
			getContractinfo(touchLineinfo.value.id, touchLineinfo.value.contractid).then(() => {
				pageSetting.value.presentProjectID = line.id;
				pageSetting.value.presentContractID = line.contractid;
				// console.log('contractInfos', contractInfos.value);
				// console.log('touchLineinfo', touchLineinfo.value);
				getTaskinfo(touchLineinfo.value.id);
			});
		}

		if (line_cache.value.length > 1) {
			if (line.index == 0) {
				touchLine_right.value = line_cache.value[line.index + 1];
				touchLine_left.value = 'None';
			} else if (line.index == line_cache.value.length - 1) {
				touchLine_left.value = line_cache.value[line.index - 1];
				touchLine_right.value = 'None';
			} else {
				touchLine_left.value = line_cache.value[line.index - 1];
				touchLine_right.value = line_cache.value[line.index + 1];
			}
		}
	};
	//找到点击区域的图形线信息，判断是否为可拖动状态
	const isDrag = (x, y) => {
		y = y - topBoxHeight.value;
		x = x - leftEdgeWeight.value;
		touchLine_left.value = 'None';
		touchLine_right.value = 'None';
		let midX = 0;
		for (const line of line_cache.value) {
			if (y >= line.y - pageSetting.value.lineWidth +
				pageSetting.value.topY && y <= line.y + pageSetting.value.lineWidth +
				pageSetting.value.topY) {
				defineThreelinesinfo(line);
				drawShadowLine();
				drawPointer();
				drawAxisX('showpointer');
				// pageSetting.value.canMove = true;   此版不带拖动功能
				// console.log("x:",x,"y:",y,"midX",midX,"line info:",line);
				if ((x >= line.x1 - 20 && x <= line.x1 + 20) || (x >= line.x2 - 20 && x <= line.x2 + 20)) {
					midX = (line.x1 + line.x2) / 2;
					if (x <= midX) {
						pageSetting.value.direction = 'left'
					} else {
						pageSetting.value.direction = 'right'
					}
					pageSetting.value.isDragging = true;
				}

				return;
			}
		}
		drawShadowLine('clear');
		cleanDrawpointer();
		// console.log(pageSetting.value.pointerID);
		clearInterval(pageSetting.value.pointerID);
		pageSetting.value.pointerID = 0;
		drawAxisX('');
		touchLineinfo.value = 'None';
		pageSetting.value.canMove = false;
	};
	const handleCanvasClick = (event) => {
		console.log(event)
		const touch = event.touches[0];
		setTimeout(() => {
			isDrag(touch.clientX, touch.clientY);
		}, 0);
	}
	//按下后判断事件
	const handleTouchStart = (event) => {
		const touch = event.touches[0];
		// console.log('touchinfo',touch);
		// console.log('topBoxHeight.value',topBoxHeight.value);
		setTimeout(() => {
			// isDrag(touch.x, touch.y);
			isDrag(touch.clientX, touch.clientY);
		}, 0);
	};
	//核心移动规则,非H5环境不可使用
	const handleTouchMove = (event) => {
		const touch = event.touches[0];
		if (pageSetting.value.isDragging && pageSetting.value.canMove === true) {
			//多线程线条规则判断，至少留一个像素
			if (pageSetting.value.direction == 'left') {
				if (touch.x > pageSetting.value.drawX && touch.x < touchLineinfo.value.x2) {
					touchLineinfo.value.x1 = touch.x;
				} else if (touch.x <= pageSetting.value.drawX) {
					touchLineinfo.value.x1 = pageSetting.value.drawX;
					overAreatips();
				} else if (touch.x >= touchLineinfo.value.x2) {
					touchLineinfo.value.x1 = touchLineinfo.value.x2 - 1;
				}
			} else {
				if (touch.x < screenWidth - pageSetting.value.endX && touch.x > touchLineinfo.value.x1) {
					touchLineinfo.value.x2 = touch.x;
				} else if (touch.x <= touchLineinfo.value.x1) {
					touchLineinfo.value.x2 = touchLineinfo.value.x1 + 1;
				} else if (touch.x >= screenWidth - pageSetting.value.endX) {
					touchLineinfo.value.x2 = screenWidth - pageSetting.value.endX;
					overAreatips();
				}
			}
			drawLine(touchLineinfo.value, 'move');
			calculateTimeoftouchLine();
			drawPointer();
			drawAxisX('showpointer');
		}
	};
	//抬手后事件
	const handleTouchEnd = (event) => {
		if (!pageSetting.value.canMove) { //没有拖动甘特图线时，抬手无动作
			return;
		} else {
			pageSetting.value.isDragging = false;
			pageSetting.value.direction = 'right';
			pageSetting.value.canMove = false;
			dataTransfer(touchLineinfo.value);
			drawLine(touchLineinfo.value, 'show');
		}

	};
	//多线程任务展示
	const mutiplyShow = (drawtype) => {
		let n = 0;
		let drawInterval = 130; //画线的时间间隔
		for (const line of line_cache.value) {
			line.y = pageSetting.value.drawY;
			if (line.index != 0) {
				line.y = line.y + pageSetting.value.intervalY * line.index;
			}
			if (drawtype == 'animation') {
				setTimeout(() => {
					line.drawID = setInterval(() => drawLineAnimation(line), parseInt(1000 /
						pageSetting.value.fps));
				}, n * drawInterval);
				n++;
			} else {
				drawLine(line, 'show');
			}
		}
	};

	const generateYearRange = () => {
		const currentYear = new Date().getFullYear();
		for (let i = 2020; i <= currentYear + 1; i++) {
			yearRange.value.push({
				text: i.toString(),
				value: i
			});
		}
	};

	//计算根据移动数据而产生的时间变化，只在可使用交互移动时才生效
	const calculateTimeoftouchLine = () => {
		let x1 = touchLineinfo.value.x1;
		let x2 = touchLineinfo.value.x2;
		let startpoint = new Date(pageSetting.value.startpoint);
		let x1_point = 0;
		let x2_point = 0;
		if (pageSetting.value.timeType === 'hour') {
			x1_point = parseInt((x1 - pageSetting.value.drawX) * pageSetting.value.durationMinutes / valueX);
			x2_point = parseInt((x2 - pageSetting.value.drawX) * pageSetting.value.durationMinutes / valueX);
			startpoint.setMinutes(startpoint.getMinutes() + x1_point);
			touchLineinfo.value.start = formatTimedata(startpoint).wholeTime;

			startpoint = new Date(pageSetting.value.startpoint);
			startpoint.setMinutes(startpoint.getMinutes() + x2_point);
			touchLineinfo.value.end = formatTimedata(startpoint).wholeTime;
		} else {
			x1_point = parseInt((x1 - pageSetting.value.drawX) * pageSetting.value.durationDays / valueX);
			x2_point = parseInt((x2 - pageSetting.value.drawX) * pageSetting.value.durationDays / valueX);
			startpoint.setDate(startpoint.getDate() + x1_point);
			touchLineinfo.value.start = formatTimedata(startpoint).date;

			startpoint = new Date(pageSetting.value.startpoint);
			startpoint.setDate(startpoint.getDate() + x2_point - 1);
			touchLineinfo.value.end = formatTimedata(startpoint).date;
		}
	};
	//计算天数或分钟
	const countTimes = (start, end) => {
		const startTime = new Date(start);
		const endTime = new Date(end);
		let diff = endTime - startTime;
		let diffDays = diff / (1000 * 60 * 60 * 24) + 1;
		let diffMinutes = diff / (1000 * 60);
		if (pageSetting.value.timeType == 'hour') {
			return diffMinutes;
		} else {
			return diffDays;
		}
	};
	//按项目找到整个时间轴区间
	const findPeriod = (type, year, sdate, edate) => {
		let minX1 = '';
		let maxX2 = '';
		if (type == 'all') {
			let j1 = year + '-01-01 00:00:00';
			let d31 = year + '-12-31 23:59:59';
			minX1 = new Date(Math.min(new Date(j1).getTime()));
			maxX2 = new Date(Math.min(new Date(d31).getTime()));
		} else if (type == 'auto') {
			minX1 = new Date(Math.min(...line_cache.value.map(obj => new Date(obj.start).getTime())));
			maxX2 = new Date(Math.max(...line_cache.value.map(obj => new Date(obj.end).getTime())));
		} else if (type == 'project') {
			minX1 = new Date(Math.min(new Date(sdate).getTime()));
			maxX2 = new Date(Math.min(new Date(edate).getTime()));
		}
		pageSetting.value.startpoint = pageSetting.value.timeType === 'month' ? formatTimedata(minX1)
			.firstDayOfMonth :
			formatTimedata(minX1).startclock;
		pageSetting.value.endpoint = pageSetting.value.timeType === 'month' ? formatTimedata(maxX2)
			.lastDayOfMonth :
			formatTimedata(maxX2).endclock;
		let diff = new Date(pageSetting.value.endpoint) - new Date(pageSetting.value.startpoint);
		pageSetting.value.durationDays = parseInt(diff / (1000 * 60 * 60 * 24)) + 1;
		pageSetting.value.durationMinutes = parseInt(diff / (1000 * 60)) + 1;
	};

	//格式化时间
	const formatTimedata = (date) => {
		let year = date.getFullYear();
		let month = date.getMonth() + 1; // getMonth 返回的月份从 0 开始，所以需要加 1
		let day = date.getDate();
		let hours = date.getHours();
		let minutes = date.getMinutes();
		let seconds = date.getSeconds();
		// 如果月或日的数字小于 10，前面添加一个 '0'
		if (month < 10) month = '0' + month;
		if (day < 10) day = '0' + day;
		if (hours < 10) hours = '0' + hours;
		if (minutes < 10) minutes = '0' + minutes;
		if (seconds > 30) minutes += 1;

		let lastDayOfMonth = `${year}-${month}-${new Date(year, month, 0).getDate()} 23:59:59`; // 获取当月的最后一天
		let firstDayOfMonth = `${year}-${month}-01 00:00:00`; // 获取当月的最后一天
		let thedate = `${year}-${month}-${day}`;
		let time = `${hours}:${minutes}:00`;
		return {
			date: thedate,
			minutes: time,
			wholeTime: `${thedate} ${time}`,
			startclock: `${thedate} ${hours}:00:00`,
			endclock: `${thedate} ${hours+1}:00:00`,
			firstDayOfMonth: firstDayOfMonth,
			lastDayOfMonth: lastDayOfMonth,
		};
	};
	//坐标变换后生成新的可用line数据
	const dataTransfer = (line) => {
		let type = pageSetting.value.timeType;
		let durationperiods = type === 'hour' ? pageSetting.value.durationMinutes : pageSetting.value.durationDays;
		let this_duration = countTimes(line.start, line.end);
		let x1_point = countTimes(pageSetting.value.startpoint, line.start);
		x1_point = type === 'hour' ? x1_point : x1_point - 1;
		if (line.colorkey === '') {
			line.colorkey = findMinNotExist(coloredPool, orgGCP);
			line.color = ganttColor.value.find(obj => obj.key === line.colorkey).value;
			coloredPool.push(line.colorkey);
		}
		line.x1 = parseInt(pageSetting.value.drawX + x1_point * valueX / durationperiods);
		line.x2 = parseInt(line.x1 + valueX * this_duration / durationperiods);
		line.xp = parseInt(line.x1 + line.percent * (line.x2 - line.x1) / 100);
		return line;
	};

	//新增一条线体
	const addNewline = () => {
		let idx = line_cache.value.length;
		let n = findMinNotExist(coloredPool, orgGCP);
		let newLine = {
			id: generateID(),
			start: line_cache.value[idx - 1].start,
			end: line_cache.value[idx - 1].end,
			x1: line_cache.value[idx - 1].x1,
			y: line_cache.value[idx - 1].y + pageSetting.value.intervalY,
			x2: line_cache.value[idx - 1].x2,
			xp: line_cache.value[idx - 1].x1,
			index: idx,
			colorkey: n,
			color: ganttColor.value.find(obj => obj.key === n).value,
			text: '',
			drawID: 0,
			drawStep: 0,
			drewX: 0,
			percent: 0,
		}

		coloredPool.push(n);
		line_cache.value.push(newLine);
		touchLineinfo.value = newLine;
		pageSetting.value.isEdit = true;
		pageSetting.value.addNew = true;
		// console.log(line_cache.value);
		cleanDrawgantt();
		mutiplyShow();
		drawShadowLine();
	};
	// 删除线
	const deleteLine = () => {
		const filteredLine = line_cache.value.map((line, index) => {
			return index !== touchLineinfo.value.index ? line : undefined;
		}).filter(line => line !== undefined);
		// console.log(filteredLine);
		const lineNum = Math.max(filteredLine.length, line_cache.value.length - 1);
		line_cache.value = filteredLine; /*更新所有线体数据*/
		for (let i = touchLineinfo.value.index; i < lineNum; i++) { //更新线体索引
			line_cache.value[i].index--;
		}
		removeColorkey(touchLineinfo.value.colorkey);
		pageSetting.value.canvasHeight = pageSetting.value.canvasHeight - 40;
		cleanDrawgantt();
		mutiplyShow();
		drawShadowLine('clear');
		touchLineinfo.value = 'None'; //清除选中线体数据
	}
	//重新排序
	const reIndex = async () => {
		cleanDrawpointer();
		cleanDrawgantt();
		findPeriod();
		let id = '';
		line_cache.value.sort((a, b) => a.x1 - b.x1);
		let idx = 0;
		for (const line of line_cache.value) {
			line.index = idx;
			dataTransfer(line);
			// console.log(touchLineinfo.value);
			if (touchLineinfo.value !== 'None') {
				if (line.id === touchLineinfo.value.id) {
					touchLineinfo.value = line;
				}
			}
			idx++;
		}
		await mutiplyShow('animation');
		if (touchLineinfo.value !== 'None') {
			isDrag(touchLineinfo.value.x1, pageSetting.value.drawY + pageSetting.value.intervalY * (touchLineinfo
				.value
				.index));
			drawShadowLine();
		} else {
			drawShadowLine('clear');
		}

	};
	//保存线数据
	const saveLinedata = () => {
		if (touchLineinfo.value.text != '') {
			pageSetting.value.isEdit = false;
			pageSetting.value.canSave = false;
			pageSetting.value.canvasHeight = pageSetting.value.addNew ? pageSetting.value.canvasHeight + 40 :
				pageSetting.value.canvasHeight;
			pageSetting.value.addNew = false;
			let ps = new Date(pageSetting.value.startpoint);
			let pe = new Date(pageSetting.value.endpoint);
			let ns = new Date(touchLineinfo.value.start);
			let ne = new Date(touchLineinfo.value.end);
			cleanDrawgantt();
			if (ns < ps || ne > pe) {
				findPeriod();
				for (const line of line_cache.value) {
					dataTransfer(line);
				}
				mutiplyShow('animation');
			} else {
				dataTransfer(touchLineinfo.value);
				mutiplyShow();
			}
			drawAxisX('showpointer');
			drawPointer();
		}
	};
	//取消编辑
	const cancelEdit = () => {
		pageSetting.value.isEdit = false;
		if (pageSetting.value.addNew === true) {
			removeElementById(touchLineinfo.value.id);
			let idx = 0;
			for (const line of line_cache.value) {
				line.index = idx;
				idx++;
			}
			removeColorkey(touchLineinfo.value.colorkey); //新增时取消，移除颜色池中对应的key
			pageSetting.value.addNew === false;
			drawShadowLine('clear');
		}
		cleanDrawgantt();
		mutiplyShow();
	};
	//按ID删除线元素
	const removeElementById = (id) => {
		const index = line_cache.value.findIndex((item) => item.id === id);
		if (index !== -1) {
			line_cache.value.splice(index, 1);
		}
	};
	//生成一个新的ID
	const generateID = () => {
		let id = '';
		const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		for (let i = 0; i < 32; i++) {
			id += characters.charAt(Math.floor(Math.random() * characters.length));
		}
		return id;
	};
	//计算调和函数y=1/x下的总步数
	const calTotalStep = (m) => {
		let sum = 0;
		for (let n = 1; n <= m; n++) {
			sum = sum + m / n;
		}
		return sum;
	};
	//找到当前帧的px步长
	const getStep = (lineLength, fps, TotalStep, stepn) => {
		// console.log(lineLength, fps, TotalStep, stepn);
		let stepx = lineLength * (fps / stepn / TotalStep);
		if (stepn <= 5) {
			//前5帧逐渐加快
			stepx = parseInt(stepx * (stepn / 10))
		} else if (stepn > 5 && stepn < 20) {
			stepx = parseInt(stepx * (1 + stepn / 10))
		} else {
			stepx = parseInt(stepx * (1 + stepn / 40))
		}
		stepx = stepx < 3 ? 3 : stepx;
		return stepx;
	};
	//处理颜色的透明度
	const colorOpacity = (color, opacity) => {
		let rgb = '';
		if (color.length > 10) {
			rgb = color.slice(5, -1).split(",");
			rgb = `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${opacity})`;
		} else {
			rgb =
				`rgba(${parseInt(color.slice(1, 3),16)}, ${parseInt(color.slice(3, 5),16)}, ${parseInt(color.slice(5, 7),16)}, ${opacity})`;
		}
		return rgb;
	};
	//查找未用到的颜色最小值
	const findMinNotExist = (a, b) => {
		let n = b.find(element => !a.includes(element));
		//当颜色池满了后，清空颜色池，重新开始记数；
		if (typeof n === 'undefined') {
			n = 1;
			coloredPool = [];
		}
		return n;
	};
	//从已用颜色池中删掉某个颜色的key
	const removeColorkey = (colorkey) => {
		let index = coloredPool.indexOf(colorkey);
		if (index !== -1) {
			coloredPool.splice(index, 1);
		}
	};
	//越界提示
	const overAreatips = () => {
		uni.showToast({
			title: '超出时间范围，请点击编辑',
			icon: 'none',
			position: 'top'
		})
	};

	const chooseMember = (memberInfo) => {
		proxy.$refs.popup.open('center');
		drawAxisX1('');
	};
	//页面初始化
	const init = () => {
		const currentYear = new Date().getFullYear();
		ganttSeachsetting.value.period = currentYear;
		generateYearRange();
		getGantt_TopInfos(ganttSeachsetting.value.period, '').then(() => {
			pageSetting.value.showTopinfo = true;
			topInfos.value.data2.forEach((item) => {
				item.value = parseInt(item.no);
				item.text = item.teamname;
				delete item.no;
				delete item.teamname;
			});
			topInfos.value.data2.push({
				value: 0,
				text: "全公司"
			});
			topInfos.value.data2.sort((a, b) => a.value - b.value);
		});
		//计算绘制甘特图的动画总步长
		pageSetting.value.totalStep = calTotalStep(pageSetting.value.smooth);
		//设置线条颜色库中所有颜色的透明度
		ganttColor.value.forEach((item, index) => {
			item.value = colorOpacity(item.value, 0.6);
		});
		//设置原始颜色池的数组
		orgGCP = Array.from({
			length: ganttColor.value.length
		}, (_, i) => i + 1);
	};

	const isVisible = ref(true); // 默认iframe是可见的
	// 定义一个处理窗口大小变化的函数  
	const handleVisibilityChange = () => {
		console.log("可见状态变更");
		isVisible.value = !document.hidden;
	};

	onMounted(() => {
		console.log("页面加载");
		document.addEventListener('visibilitychange', handleVisibilityChange);
		nextTick(() => {
			// DOM 更新完成后执行的代码
			console.log(topBox.value, topBox.value.offsetHeight)
			if (topBox.value) {
				uni.createSelectorQuery()
					.select('.topBox') //选择你要获取尺寸的盒子元素，这里假设盒子元素的class为box
					.boundingClientRect((rect) => {
						console.log(rect)
						const boxwidth = rect.width; // 盒子的宽度，单位为px
						const boxHeight = rect.height; //盒子的高度，单位为px
						console.log('盒子宽度:', boxwidth);
						console.log('盒子高度:', boxHeight);
					})
					.exec();
			}
		});
		init();
		getGanttDatas(ganttSeachsetting.value.period, '');
	})
	onUnmounted(() => {
		document.removeEventListener('visibilitychange', handleVisibilityChange);
	});
	const closepopup=()=>{
			proxy.$refs.popup.close('center');
	}
	// --检测父iframe是否可见
	function checkVisibility() {
		if (typeof window.parent.isIframeVisible !== 'undefined') {
			// 直接访问（注意：这种方法可能导致安全问题）  
			console.log('Iframe visibility from parent:', window.parent.isIframeVisible);

		} else {
			// 使用localStorage（更安全）  
			localStorage.getItem('isIframeVisible', function(result) {
				console.log('Iframe visibility from localStorage:', result);
				// 注意：localStorage.getItem()实际上不是异步的，这里只是为了说明  
			});
			// 但实际上，你应该直接检查localStorage  
			var isVisible = localStorage.getItem('isIframeVisible') === 'true';
			console.log('Iframe visibility from localStorage:', isVisible);

		}
	}

	function areAllValuesEmpty(obj) {
		let _obj = {
			...obj
		};
		delete _obj.no;
		// 遍历对象的每个属性
		for (let key in _obj) {
			if (_obj.hasOwnProperty(key)) {
				const value = _obj[key];

				// 如果属性值是对象，递归检查
				if (typeof value === 'object' && value !== null) {
					if (!areAllValuesEmpty(value)) {
						return false;
					}
				} else {
					// 如果属性值不是空或者未定义，则返回false
					if (value !== null && value !== undefined && value !== '') {
						return false;
					}
				}
			}
			// 如果所有属性值都是空或者未定义，则返回true
			return true;
		}
	}
</script>

<style lang="scss">
	.buttonarea {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		margin-right: 20px;

		.button {
			width: 80px;
			height: 30px;
			background-color: green;
			line-height: 30px;
			font-size: 14px;
			color: white;
			border-radius: 20px;
			margin-left: 10px;
			margin-top: 10px;
		}
	}

	.members {
		display: inline-block;
		margin-right: 10px;
	}

	.topSet {
		display: flex;
		flex-direction: row;
		justify-content: flex-end;

		.cctype {
			width: 250rpx;
			padding: 5px;
		}
	}

	.uni-forms-item {
		margin-bottom: 5rpx !important;

		.members {
			line-height: 30px;
		}

		text {
			line-height: 30px;
		}
	}

	.uni-forms-item__label {
		height: 28px;
	}

	.pageing {
		.btn {
			font-size: 14px;
			display: flex;
			align-items: center;
			padding: 3px 15px 3px 5px;
			height: 35px;
			margin: 0 5px;
			cursor: pointer;

			text {
				font-size: 14px;
			}

			.icon {
				height: 35px;
				line-height: 35px;
			}
		}
	}
</style>